package com.echo.im.server.config;

import com.echo.im.mq.contant.QueueConstants;
import com.echo.im.server.netty.IMServerGroup;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

/**
 * RabbitMQ 配置类
 * @author echo
 * @date 2024-08-15
 */
@Configuration
@DependsOn("IMServerGroup") //等待im-server启动好了之后获取serverId之后开始绑定队列
public class RabbitMqConfig {

    @Bean
    DirectExchange pushDirect() {
        return ExchangeBuilder
                .directExchange(QueueConstants.ECHO_EXCHANGE)
                .durable(true)
                .build();
    }

    @Bean
    public Queue pushPrivateQueue() {
        return new Queue(join(QueueConstants.PUSH_PRIVATE_QUEUE, IMServerGroup.serverId));
    }

    @Bean
    public Queue pushGroupQueue() {
        return new Queue(join(QueueConstants.PUSH_GROUP_QUEUE, IMServerGroup.serverId));
    }

    @Bean
    public Queue pushSystemQueue() {
        return new Queue(join(QueueConstants.PUSH_SYSTEM_QUEUE, IMServerGroup.serverId));
    }

    @Bean
    public Queue platformCommandQueue() {
        return new Queue(join(QueueConstants.PLATFORM_COMMAND_QUEUE, IMServerGroup.serverId));
    }


    @Bean
    Binding privatePushBinding(DirectExchange pushDirect, Queue pushPrivateQueue) {
        return BindingBuilder
                .bind(pushPrivateQueue)
                .to(pushDirect)
                .with(join(QueueConstants.PUSH_PRIVATE_TOPIC, IMServerGroup.serverId));
    }

    @Bean
    Binding groupPushBinding(DirectExchange pushDirect, Queue pushGroupQueue) {
        return BindingBuilder
                .bind(pushGroupQueue)
                .to(pushDirect)
                .with(join(QueueConstants.PUSH_GROUP_TOPIC, IMServerGroup.serverId));
    }

    @Bean
    Binding systemPushBinding(DirectExchange pushDirect, Queue pushSystemQueue) {
        return BindingBuilder
                .bind(pushSystemQueue)
                .to(pushDirect)
                .with(join(QueueConstants.PUSH_SYSTEM_TOPIC, IMServerGroup.serverId));
    }

    @Bean
    Binding platformCommadnBinding(DirectExchange pushDirect, Queue platformCommandQueue) {
        return BindingBuilder
                .bind(platformCommandQueue)
                .to(pushDirect)
                .with(join(QueueConstants.PLATFORM_COMMAND_TOPIC, IMServerGroup.serverId));
    }


    private String join(String str, Long serverId) {
        return str + "." + serverId.toString();
    }
}
